package youleche.com.controler.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import youleche.com.business.BEmailConfig;
import youleche.com.caches.CacheFactory;
import youleche.com.common.ParamConfigParameters;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.model.MEmailConfig;
import youleche.com.util.AESEncryptAndDecrypt;
import youleche.com.util.JsonHelper;

/**
 * Servlet implementation class SEmailConfigServlet
 */
public class SEmailConfigServlet extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;

	public SEmailConfigServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int action = Integer.parseInt(request.getParameter("action"));
		switch (action) {
		case 0:
			// 添加邮件配置
			this.addEmailConfig(request, response);
			break;
		case 1:
			// 禁用和启用
			this.forbiddenAndStart(request, response);
			break;
		case 2:
			// 获取列表数据
			this.getConfigList(request, response);
			break;
		case 3:
			// 根据id获取数据
			this.getConfigById(request, response);
			break;
		case 4:
			// 根据id删除配置
			this.deleteConfigById(request, response);
			break;
		}
	}

	/**
	 * 根据id删除配置
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 */
	private void deleteConfigById(HttpServletRequest request,
			HttpServletResponse response) {
		String keyId = request.getParameter("keyId");
		BEmailConfig handler = new BEmailConfig();
		String result = "0";
		try {
			if (handler.deleteConfigById(keyId) > 0) {
				CacheFactory.getEmailConfigCache().updateCache();
				result = "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.response(response, result);
	}

	/**
	 * 根据id获取配置
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	private void getConfigById(HttpServletRequest request,
			HttpServletResponse response) {
		List<MEmailConfig> list = null;
		try {
			list = (List<MEmailConfig>) CacheFactory.getEmailConfigCache()
					.getCache();
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (list != null) {

		}
	}

	/**
	 * 获取列表数据
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	private void getConfigList(HttpServletRequest request,
			HttpServletResponse response) {
		List<MEmailConfig> list = null;
		try {
			list = (List<MEmailConfig>) CacheFactory.getEmailConfigCache()
					.getCache();
			if (list != null) {
				List<MEmailConfig> configList = new LinkedList<MEmailConfig>();
				for (MEmailConfig m : list) {
					m.setUserPassword("");
					configList.add(m);
				}

				JsonHelper.printListToJsonString(response, configList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 禁用和启用
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 */
	private void forbiddenAndStart(HttpServletRequest request,
			HttpServletResponse response) {
		boolean isForbidden = "0".equals(request.getParameter("mark"));
		String keyId = request.getParameter("keyId");
		BEmailConfig handler = new BEmailConfig();
		String result = "0";
		try {
			if (!isForbidden) {
				// 启用一个邮箱配置时其他另外一个启用的必须禁用，这里自动禁用
				@SuppressWarnings({ "unchecked", "static-access" })
				List<MEmailConfig> list = (List<MEmailConfig>) CacheFactory
						.getEmailConfigCache().getCache();
				if (list != null && list.size() > 0) {
					for (MEmailConfig config : list) {
						if ("1".equals(config.getA1())) {
							handler.udpateRemarkById(config.getId(), true);
						}
					}
				}
			}

			if (handler.udpateRemarkById(keyId, isForbidden) > 0) {
				CacheFactory.getEmailConfigCache().updateCache();
				result = "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.response(response, result);
	}

	/**
	 * 添加邮件配置
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 */
	private void addEmailConfig(HttpServletRequest request,
			HttpServletResponse response) {
		BEmailConfig handler = new BEmailConfig();
		MEmailConfig config;
		String result = "0";
		try {
			config = (MEmailConfig) JsonHelper.getObjectByJsonString(request,
					MEmailConfig.class);
			config.setEmailContent(this.getEmailContent(request));
			config.setEmailUserName(config.getEmail());
			config.setEmailType(config.getEmail().split("\\@")[1]);
			ParamConfigParameters param = new ParamConfigParameters();
			String key = param.getParameter("EmailPassword_KEY");
			config.setUserPassword(AESEncryptAndDecrypt.encrypt(
					config.getUserPassword(), key));
			config.setA1("0");
			if (handler.addEmailConfig(config) > 0) {
				// 更新缓存
				CacheFactory.getEmailConfigCache().updateCache();
				result = "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.response(response, result);
	}

	/**
	 * 获取邮件内容
	 * 
	 * @param request
	 * @return
	 */
	private String getEmailContent(HttpServletRequest request) {
		String content = " ";
		String path = System.getProperty("user.dir")
				+ "\\WebContent\\admin\\emailContent.html";
		File file = new File(path);
		StringBuffer sb = new StringBuffer();
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isReader = new InputStreamReader(fis);
			BufferedReader reader = new BufferedReader(isReader);
			while((content = reader.readLine()) != null){
				sb.append(content + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//		Pattern pattern = Pattern.compile("<div(.*?)");
//		Matcher mat = pattern.matcher(sb.toString());
//		System.out.println(sb.toString());
//		System.out.println("===================");
//		while(mat.find()){
//			System.out.println(mat.group(1));
//		}
		
		System.out.println(sb.toString());
		
		return sb.toString();
	}

	public static void main(String[] args) {
		SEmailConfigServlet h = new SEmailConfigServlet();
		h.getEmailContent(null);
	}
}
